package com.kis.core;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NoSuchObjectException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.kis.core.emnu.PropertiesType;

public class Core {
	String packagePath = Utils.readProperties(PropertiesType.SCANPACKAGE.getValue());
	String ipPath = Utils.readProperties(PropertiesType.ADDRESS.getValue());
	String port = Utils.readProperties(PropertiesType.PORT.getValue());
	Map<String,Object> results=new HashMap<String, Object>();
	Registry registry=null;
	public Map<String,Object> run() {
		results.clear();
		String msg = "";
		boolean result = true;
		List<String> services = Utils.assService(packagePath, true);
		try {
			registry=LocateRegistry.createRegistry(Integer.parseInt(port));
			for (String string : services) {
				String classPath = packagePath + "." + string.split("\\.")[0] + ".impl." + string.split("\\.")[1] + "Impl";
				try {
					Object c = Class.forName(classPath).newInstance();
					String bindAddress = ipPath + ":" + port + "/" + Utils.visitPath(string);
					System.out.println(bindAddress);
					Naming.rebind(bindAddress, (Remote) c);
				} catch (InstantiationException e) {
					result = false;
					e.printStackTrace();
					msg=e.getMessage();
				} catch (IllegalAccessException e) {
					result = false;
					e.printStackTrace();
					msg=e.getMessage();
				} catch (ClassNotFoundException e) {
					result = false;
					msg=e.getMessage();
					e.printStackTrace();
				} catch (RemoteException e) {
					result = false;
					msg=e.getMessage();
					e.printStackTrace();
				} catch (MalformedURLException e) {
					result = false;
					msg=e.getMessage();
					e.printStackTrace();
				}
			}
		} catch (RemoteException e1) {
			result = false;
			msg=e1.getMessage();
			e1.printStackTrace();
		}
		System.out.println("--------------------------------------");
		System.out.println("|          启动成功。。。。。。。                                          |");
		System.out.println("--------------------------------------");
		results.put("result", result);
		results.put("msg", msg);
		return results;
	}
	public Map<String,Object> stop(){
		boolean result =true;
		String msg = "";
		try {
			Registry registry = LocateRegistry.createRegistry(Integer.parseInt(port));
			UnicastRemoteObject.unexportObject(registry, true);
		} catch (NumberFormatException e) {
			result=false;
			msg=e.getMessage();
			e.printStackTrace();
		} catch (RemoteException e) {
			result=false;
			msg=e.getMessage();
			e.printStackTrace();
		}
		System.exit(0);
		results.put("msg", msg);
		results.put("result", result);
		return results;
	}
}
